import Promise from 'bluebird';
import redis from '../app/lib/redis';
import cfgAll from './cfg';


const {redis: cfg} = cfgAll;
const redisOpts = {
    ...cfg,
    host: cfg.host || '127.0.0.1',
    port: cfg.port || 6379,
    password: cfg.password,
    database: cfg.database === undefined ? 0 : cfg.database,
};

/**
 * 初始化redis
 */
export const init = () => {
    redis.init(redisOpts);
};

/**
 * 存储接口获取用户微信信息时用的scope值
 * @param data
 */
export const setUserWeiXinScope = data => new Promise((resolve) => {
    if (data.openid) {
        const key = `user:${data.openid}`;
        redis.set(key, data.scope);
        redis.expire(key, 1 * 60 * 10); //有效期10分钟
    }
    resolve(data);
});

/**
 * 获取scope值
 * @param userRaw
 */
export const getUserWeiXinScope = data => new Promise((resolve) => {
    const key = `user:${data.openid}`;
    redis.get(key, (err, str) => {
        if (str) {
            // snsapi_userinfo只读取一次，读取后删除
            if (str === 'snsapi_userinfo') {
                redis.set(key, '');
                redis.expire(key, 1 * 60 * 10); //有效期10分钟
            }
            resolve(str);
        } else {
            resolve('');
        }
    });
});
